package protocol

import (
	"encoding/json"
	"fmt"
)

//JSONMessage 长连接用到的协议
type JSONMessage struct {
	Type int    //消息类型
	Body []byte //json字符串
}

//JSONProtocol 使用JSON 进行序列化
type JSONProtocol struct {
}

//协议类型
const (
	SPHEART = 1 //心跳包
)

//Marshal 序列化
func (jn *JSONProtocol) Marshal(body interface{}) ([]byte, error) {
	jb, err := json.Marshal(body)
	if err != nil {
		return nil, err
	}
	jm := &JSONMessage{Type: 0, Body: jb}

	switch body.(type) {
	case Heart:
		jm.Type = SPHEART
	default:
		return nil, fmt.Errorf("Marshal not support type %v", jm)
	}
	return json.Marshal(jm)
}

//Unmarshal 反序列化
func (jn *JSONProtocol) Unmarshal(msg []byte) (interface{}, error) {
	jm := &JSONMessage{}
	err := json.Unmarshal(msg, jm)
	if err != nil {
		return nil, err
	}
	var ret interface{}
	switch jm.Type {
	case SPHEART:
		body := &Heart{}
		err = json.Unmarshal(jm.Body, &body)
		if err != nil {
			ret = body
		}
	default:
		return nil, fmt.Errorf("Unmarshal not support type %v", jm)
	}
	return ret, err
}
